package cn.zyjblogs.config.security;

import cn.zyjblogs.server.user.service.impl.OauthUserDetailsServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    private final OauthUserDetailsServiceImpl userDetailsService;
    private final OauthAuthenticationProvider oauthAuthenticationProvider;
    private final PasswordEncoder passwordEncoder;
//    private final CsrfTokenRepository oauthCsrfTokenRepository;
    /**
     * 密码编码解码
     *
     * @return
     */


    /**
     * 认证管理器
     *
     * @param
     * @return org.springframework.security.authentication.AuthenticationManager
     * @author zhuyijun
     * @date 2022/8/17 下午9:56
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(oauthAuthenticationProvider)
                .userDetailsService(userDetailsService)
                .passwordEncoder(passwordEncoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        //使HttpSecurity接收以"/login/","/oauth/"开头请求, 配置HttpSecurity不阻止swagger页面
        http
//                .requestMatchers().antMatchers("/login")
//                .and()
                .authorizeRequests()

//                .antMatchers("/webjars/**", "/swagger-ui.html/**", "/swagger-resources/**", "/v2/api-docs/**")
//                .permitAll()
//                .antMatchers("/user/logout", "/login", "/oauth/**", "/user/login", "/user/refresh/token").permitAll()
                //以下请求必须认证通过
                .anyRequest().authenticated()
                .and()
                //允许表单登录
                .formLogin()
//                .loginPage("/login").loginProcessingUrl("/v1/user/login")
                .and()
                .httpBasic();
    }


    @Override
    public void configure(WebSecurity web) {
//        web.ignoring().antMatchers("/user/robot-token");
    }

}